﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using System.Collections.ObjectModel;
using DoubleH.Utility;
using System.Collections;
using System.Data;
using System.IO;
using System.Windows.Threading;
using System.Diagnostics;
using System.Collections.Specialized;
using DoubleH.Utility.Configuration;

namespace ProductS.UC
{
    /// <summary>
    /// 商品编辑控件，自动根据配置是否允许负库存销售并计算所有相关值
    /// </summary>
    public partial class ProductSListInfo : UserControl
    {
        public ProductSListInfo()
        {
            InitializeComponent();

            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
                return;

            InitVar();
            InitMenu();
            InitEvent();
        }

        ObservableCollection<Table.ProductS> productSinObject = new ObservableCollection<Table.ProductS>();
        DataTableText tableText;
        TextBox editTextBox = null;
        ProductS.GetProductS getProductSWindow = null;

        #region 属性
        /// <summary>
        /// 获取数据行数量
        /// </summary>
        public int Count
        {
            get { return productSinObject.Count; }
        }
        
        /// <summary>
        /// 获取或设置商品选择窗体
        /// </summary>
        public GetProductS.EnumProductS IsSale
        {
            get;
            set;
        }

        public ObservableCollection<Table.ProductS> ItemsSource
        {
            set
            {
                productSinObject = value ?? new ObservableCollection<Table.ProductS>();
                dataGridObject.ItemsSource = productSinObject;
                CalcQuantityAndMoneyOnBottom();
            }
        }
        /// <summary>
        /// 不提供底部统计功能
        /// </summary>
        public IList ItemsSourceNoCalc
        {
            get { return productSinObject; }
            set
            {
                dataGridObject.ItemsSource = value;
                //CalcQuantityAndMoneyOnBottom();
            }
        }

        bool showAverage = false;
        /// <summary>
        /// 是否显示成本(默认:false)
        /// </summary>
        public bool ShowAverage
        {
            get
            {
                return showAverage;
            }
            set
            {
                showAverage = value;
                if (showAverage)
                {
                    SumAverageMoney.Visibility = Visibility.Visible;
                    SumAverageMoneyText.Visibility = Visibility.Visible;
                }
                else
                {
                    SumAverageMoney.Visibility = Visibility.Hidden;
                    SumAverageMoneyText.Visibility = Visibility.Hidden;
                }
            }
        }

        bool canSelectProduct = true;
        /// <summary>
        /// 能否双击控件选择商品(默认:true)
        /// </summary>
        public bool CanSelectProduct
        {
            get { return canSelectProduct; }
            set { canSelectProduct = value; }
        }

        bool canNegativeSales = false;
        /// <summary>
        /// 是否允许负销售(默认:false)
        /// </summary>
        public bool CanNegativeSales
        {
            get { return canNegativeSales; }
            set { canNegativeSales = value; }
        }

        public DataGrid DataGrid
        {
            get { return dataGridObject; }
        }
        /// <summary>
        /// 获取已选择的项
        /// </summary>
        public Table.ProductS SelectedItem
        {
            get
            {
                object obj = null;
                if (dataGridObject.SelectedItem != null)
                    obj = dataGridObject.SelectedItem;
                else if (dataGridObject.SelectedCells.Count != 0)
                    obj = dataGridObject.SelectedCells[0].Item;

                if (obj == null)
                    return null;
                else
                    return obj as Table.ProductS;
            }
        }
        /// <summary>
        /// 是否显示底部合计金额(默认:true)
        /// </summary>
        public bool ShowSumMoney
        {
            get { return SumMoney.Visibility == Visibility.Visible; }
            set
            {
                SumMoney.Visibility = value ? Visibility.Visible : Visibility.Hidden;
                SumMoneyText.Visibility = value ? Visibility.Visible : Visibility.Hidden;
            }
        }

        bool showBottom = true;
        /// <summary>
        /// 是否是否显示底部(默认:true)
        /// </summary>
        public bool ShowBottom
        {
            get { return showBottom; }
            set
            {
                showBottom = value;
                ShowSumMoney = value;
                SumQuantity.Visibility = value ? Visibility.Visible : Visibility.Hidden;
                SumQuantityText.Visibility = value ? Visibility.Visible : Visibility.Hidden;
                while (gridAll.RowDefinitions.Count > 0)
                    gridAll.RowDefinitions.RemoveAt(0);
                while (gridAll.ColumnDefinitions.Count > 0)
                    gridAll.ColumnDefinitions.RemoveAt(0);
            }
        }

        /// <summary>
        /// 是否显示编辑栏右键菜单
        /// </summary>
        public bool ShowBodyContexMenu
        {
            set { dataGridObject.ShowBodyMenu = value; }
        }

        Table.CorS corS = null;
        /// <summary>
        /// 根据客户Id计算对应的会员价格
        /// </summary>
        public Table.CorS CorS
        {
            set
            {
                corS = value;
                if ((IsSale == GetProductS.EnumProductS.可采购商品 && DoubleHConfig.UserConfig.ProductPrice == 2)||IsSale==GetProductS.EnumProductS.可销售商品)
                    productSinObject.ToList<Table.ProductS>().ForEach(ps => CalcTempPrice(ps));
            }
        }

        Table.StoreS storeS = null;
        /// <summary>
        /// 设置仓库Id刷新相对应的库存和库存价
        /// </summary>
        public Table.StoreS StoreS
        {
            set
            {
                storeS = value;
                if (value == null || value.Id == -1)
                    return;

                Table.ProductS.InitQuantity(productSinObject, value.Id);
                foreach (Table.ProductS ps in productSinObject)
                    if (!CalcQuantity(ps, ps._TempQuantity, false))
                        ps._TempQuantity = 0;
            }
        }

        //bool checkStoreS = false;
        ///// <summary>
        ///// 当仓库变更时是否检查商品列表(默认:false)
        ///// </summary>
        //public bool CheckStoreS
        //{
        //    get { return checkStoreS; }
        //    set { checkStoreS = value; }
        //}

        public string EnableText
        {
            set
            {
                labelEnable.Content = value;
            }
        }

        /// <summary>
        /// 获取右键菜单
        /// </summary>
        public ContextMenu BodyMenu
        {
            get { return dataGridObject.BodyMenu; }
        }

        public bool HasItems
        {
            get
            {
                if (productSinObject.Count == 1 && productSinObject[0].Id == -1)
                    return false;

                return productSinObject.Count != 0;
            }
        }

        public bool IsReadOnly
        {
            get { return dataGridObject.IsReadOnly; }
            set
            {
                dataGridObject.IsReadOnly = value;

                if (!BodyMenu.HasItems)
                    return;

                foreach (Control con in BodyMenu.Items)
                    if (con is MenuItem)
                        con.IsEnabled = !value;

                ((MenuItem)BodyMenu.Items[BodyMenu.Items.Count - 1]).IsEnabled = true;
            }
        }

        /// <summary>
        /// 仅在 fullrow 模式下生效
        /// </summary>
        public int SelectedIndex
        {
            get
            {
                return dataGridObject.SelectedIndex;
            }
            set
            {
                if (SelectionUnit == DataGridSelectionUnit.FullRow)
                    dataGridObject.SelectedIndex = value;
            }
        }
        /// <summary>
        /// 能否自动增加新行
        /// </summary>
        public bool CanUserAddRows
        {
            get { return dataGridObject.CanUserAddRows; }
            set { dataGridObject.CanUserAddRows = value; }
        }

        public DataGridSelectionUnit SelectionUnit
        {
            get { return dataGridObject.SelectionUnit; }
            set { dataGridObject.SelectionUnit = value; }
        }
        #endregion

        #region 公共方法
        public bool InsertItem(int index, Table.ProductS obj)
        {
            if (obj == null)
                return false;

            Table.ProductS ps = productSinObject.FirstOrDefault<Table.ProductS>(f => f.Id == obj.Id);
            if (ps == null || Table.SysConfig.SysConfigParams.ProductRow)
            {
                if (!CalcQuantity(obj, 1,false))
                    return false;

                obj.InitPrice(corS);
                productSinObject.Insert(index, obj);
                CalcQuantityAndMoneyOnBottom();
                return true;
            }
            else
                return (!CalcQuantity(obj, obj._TempQuantity+1,true));
        }

        public void RemoveSelectedItem()
        {
            if (!HasItems)
                return;

            if (dataGridObject.SelectedItem != null)
                productSinObject.Remove((Table.ProductS)dataGridObject.SelectedItem);
            else
            {
                if (dataGridObject.SelectedCells.Count == 0)
                    return;

                productSinObject.Remove((Table.ProductS)dataGridObject.SelectedCells[0].Item);
            }
            CalcQuantityAndMoneyOnBottom();
        }

        /// <summary>
        /// 初始化 DataGrid 的Columns
        /// </summary>
        /// <param name="lvb"></param>
        public void InitColumns(DataGridColumnBinding lvb)
        {
            tableText = lvb.TableText;
            dataGridObject.InitColumns(lvb);
        }

        public void InitColumns(DataTableText tableText)
        {
            this.tableText = tableText;
            dataGridObject.InitColumns(tableText);
        }

        public void ResetAllProductQuantity(double newQuantity)
        {
            Debug.Assert(productSinObject != null);

            foreach (Table.ProductS ps in productSinObject)
                ps._TempQuantity = newQuantity;

            CalcQuantityAndMoneyOnBottom();
        }


        /// <summary>
        /// 检查库存是否足够
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="newValue">待出库数量</param>
        /// <param name="append">true 修改 _TempQuantity 值</param>
        /// <returns></returns>
        public bool CalcQuantity(Table.ProductS obj, double appendQuantity, bool append)
        {
            if (IsSale != GetProductS.EnumProductS.可销售商品 ||obj.Flag==Table.ProductS.EnumFlag.服务)
                return true;

            if (!canNegativeSales && appendQuantity > obj._Quantity)
            {
                MessageWindow.Show(obj.Name + " - 库存不足");
                return false;
            }
            else if (append)
            {
                obj._TempQuantity = appendQuantity;
                CalcQuantityAndMoneyOnBottom();
            }

            return true;
        }
        #endregion

        #region 私有方法
        private void InitVar()
        {
            canNegativeSales = Table.SysConfig.SysConfigParams.NegativeSales;

            labelEnable.Content = string.Empty;

            dataGridObject.ItemsSource = productSinObject;
            dataGridObject.ShowBodyMenu = true;
            
        }

        private void InitEvent()
        {
            //productSinObject.CollectionChanged += (ss, ee) => { CalcQuantityAndMoney(); };

            dataGridObject.MouseDoubleClick += (ss, ee) =>
            {
                if (IsReadOnly || !canSelectProduct)
                    return;

                if (!(ee.OriginalSource is TextBlock))
                    ShowGetProductS(false);
            };
            dataGridObject.PreparingCellForEdit += (ss, ee) => { CellEditBegin(ee); };
            dataGridObject.CellEditEnding += (ss, ee) => { CellEditEnding(ee); };
            dataGridObject.OnDelete += () => { RemoveSelectedItem(); };
            //先别删除,可能有用
            //dataGridObject.CurrentCellChanged += (ss, ee) =>
            //{
            //    if (isEditCell)
            //    {
            //        //CalcQuantityAndMoney();
            //        isEditCell = false;
            //    }
            //};
        }

        private void CellEditBegin(DataGridPreparingCellForEditEventArgs ee)
        {
            DataGridTextColumn textColumn = ee.Column as DataGridTextColumn;
            if (textColumn == null)
                return;

            string binding = ((Binding)textColumn.Binding).Path.Path;
            editTextBox = ee.EditingElement as TextBox;
            if (editTextBox == null)
                return;

            switch (binding)
            {
                case "Name":
                case "Code":
                case "Barcode":
                    editTextBox.UndoLimit = 0;//.net4.0 bug 没有它会导致TextChanged中输入中文出错
                    editTextBox.TextChanged += (s, e) =>
                    {
                        if (editTextBox == null)
                            return;

                        if (string.IsNullOrEmpty(editTextBox.Text))
                        {
                            if (getProductSWindow != null)
                            {
                                getProductSWindow.Close();
                                getProductSWindow = null;
                            }
                            return;
                        }
                        ShowGetProductS(true);
                        getProductSWindow.SearchText(editTextBox.Text, null);
                        editTextBox.Focus();
                    };
                    break;
            }
        }

        private void CellEditEnding(DataGridCellEditEndingEventArgs ee)
        {
            DataGridTextColumn textColumn = ee.Column as DataGridTextColumn;
            if (textColumn == null)
                return;

            string binding = ((Binding)textColumn.Binding).Path.Path;
            double d = 0;
            if (editTextBox == null)
                editTextBox = ee.EditingElement as TextBox;

            switch (binding)
            {
                case "_TempPrice":
                case "_AveragePrice":
                    double.TryParse(editTextBox.Text, out d);
                    editTextBox.Text = d.ToString();
                    CalcQuantityAndMoneyOnBottom();
                    break;
                case "_TempQuantity":
                    double.TryParse(editTextBox.Text, out d);
                    editTextBox.Text = d.ToString();
                    if (!CalcQuantity(SelectedItem, d, false))
                        editTextBox.Text = SelectedItem._TempQuantity.ToString();
                    break;

                case "Name":
                case "Code":
                case "Barcode":
                    if (getProductSWindow != null)
                    {
                        getProductSWindow.Close();
                        getProductSWindow = null;
                    }
                    //if (((Table.ProductS)ee.Row.Item).Id == -1)
                    //    dataGridObject.CancelEdit();
                    break;
            }

            var ps = from f in productSinObject where f.Id == -1 select f;
            for (int i = 1; i < ps.Count(); i++)
                productSinObject.Remove(ps.First());

            editTextBox = null;
            //if (getProductSWindow != null)
            //{
            //    getProductSWindow.Close();
            //    getProductSWindow = null;
            //}
        }

        private void ShowGetProductS(bool mini)
        {
            if (getProductSWindow != null)
                return;

            getProductSWindow = new GetProductS();
            getProductSWindow.Closed += (s, e) =>
            {
                if(getProductSWindow.Selected != null)
                foreach (Table.ProductS ps in getProductSWindow.Selected)
                    InsertItem(0, ps);

                getProductSWindow = null;
                editTextBox = null;
                dataGridObject.CancelEdit();
            };
            getProductSWindow.Init(IsSale, storeS);
            getProductSWindow.IsMini = mini;

            Point p = Mouse.GetPosition(this);
            Point pt = PointToScreen(Mouse.GetPosition(dataGridObject));
            getProductSWindow.Left = pt.X - p.X+300;
            getProductSWindow.Top = pt.Y - p.Y;

            if (mini)
                getProductSWindow.Show();
            else
                getProductSWindow.ShowDialog();
        }

        private void CalcTempPrice(Table.ProductS ps)
        {
            switch (DoubleHConfig.UserConfig.ProductPrice)
            {
                case 0:
                    if (IsSale == GetProductS.EnumProductS.可销售商品)
                        ps.InitPrice(corS);
                    else
                        ps._TempPrice = ps.PurchasePrice;
                    break;

                case 1:
                    DataRow row1 = FCNS.Data.SQLdata.GetDataRow("select * from ProductSIO where ProductSId=" + ps.Id + " and " + (IsSale == GetProductS.EnumProductS.可销售商品 ? "WholesalePrice<>0" : "PurchasePrice<>0"), "Id", true);
                    if (row1 == null)
                    {
                        ps._TempPrice = 0;
                        return;
                    }

                    if (IsSale == GetProductS.EnumProductS.可销售商品)
                        ps._TempPrice = (double)row1["WholesalePrice"];
                    else
                        ps._TempPrice = (double)row1["PurchasePrice"];
                    break;

                case 2:
                    DataRow row2 = FCNS.Data.SQLdata.GetDataRow("select * from ProductSIO where ProductSId=" + ps.Id + " and CorSId=" + (corS == null ? -1 : corS.Id) + " and " + (IsSale == GetProductS.EnumProductS.可销售商品 ? "WholesalePrice<>0" : "PurchasePrice<>0"), "Id", true);
                    if (row2 == null)
                    {
                        ps._TempPrice = 0;
                        return;
                    }

                    if (IsSale == GetProductS.EnumProductS.可销售商品)
                        ps._TempPrice = (double)row2["WholesalePrice"];
                    else
                        ps._TempPrice = (double)row2["PurchasePrice"];
                    break;

                default:
                    ps._TempPrice = 0;
                    break;
            }
        }

        /// <summary>
        /// 计算合计数量与合计金额
        /// </summary>
        private void CalcQuantityAndMoneyOnBottom()
        {
            if (!showBottom)
                return;

            double sumQ = 0, sumM = 0;
            foreach (Table.ProductS ps in productSinObject)
            {
                sumQ += ps._TempQuantity;
                sumM += ps._TempSum;
            }
            SumQuantity.Text = sumQ.ToString();
            SumMoney.Text = sumM.ToString();

            //计算成本
            if (!showAverage)
                return;

            double sumA = 0;
            foreach (Table.ProductS ps in productSinObject)
                sumA += ps._TempQuantity * ps._AveragePrice;

            SumAverageMoney.Text = sumA.ToString();
        }


        #endregion

        #region 菜单
        private void InitMenu()
        {
            dataGridObject.BodyMenu.Items.Add(new Separator());
            dataGridObject.BodyMenu.Items.Add(DaoRu());
            dataGridObject.BodyMenu.Items.Add(DaoChu());
            //dataGridObject.BodyMenu.Items.Add(new Separator());
            //MenuItem mi2 = new MenuItem();
            //mi2.Header = "查找单据";
            //mi2.Click += (ss, ee) =>
            //{
            //    FCNS.Data.Interface.DataIO io = new Table.ProductS();
            //    DoubleH.Utility.OpenFileWindow ofw = new OpenFileWindow();
            //    ofw.ShowDialog();
            //    foreach (Table.ProductS ps in io.Import(ofw.FileName))
            //        productSinObject.Add(ps);
            //};
            //dataGridObject.BodyMenu.Items.Add(mi1);
        }

        private MenuItem DaoRu()
        {
            MenuItem mi1 = new MenuItem();
            mi1.Header = "导入数据";
            mi1.Click += (ss, ee) =>
            {
                DoubleH.Utility.FileWindow ofw = new FileWindow();
                ofw.IsOpen = true;
                ofw.FileType = DoubleH.Utility.FileWindow.EnumFileType.商品控件的导入导出;
                ofw.ShowDialog();
                if (ofw.Canel)
                    return;

                foreach (string str in File.ReadAllLines(ofw.FileName, Encoding.UTF8))
                {
                    string[] sp = str.Split(',');
                    if (sp.Length < 6)
                        continue;

                    Table.ProductS ps = GetProductSbyDaoRu(sp[0],sp[1],sp[2]);
                    if (ps == null)
                        continue;

                    double temp = ps._TempPrice;
                    if (double.TryParse(sp[3], out temp))
                        ps._TempPrice = temp;

                    temp = 0;
                    if (double.TryParse(sp[4], out temp))
                        ps._TempQuantity = temp;

                    ps.Note = sp[5];
                    productSinObject.Add(ps);
                }
            };

            return mi1;
        }

        private Table.ProductS GetProductSbyDaoRu(string id,string code,string barCode)
        {
            Table.ProductS ps = null;
            Int64 i = -1;
            Int64.TryParse(id, out i);
            if (i != -1)
                ps = Table.ProductS.GetObject(i);
            else if (!string.IsNullOrEmpty(code))
                ps = Table.ProductS.GetObject(code);
            else if (!string.IsNullOrEmpty(barCode))
                ps = Table.ProductS.GetObject(barCode);

            return ps;
        }

        private MenuItem DaoChu()
        {
            MenuItem mi1 = new MenuItem();
            mi1.Header = "导出数据";
            mi1.Click += (ss, ee) =>
            {
                DoubleH.Utility.FileWindow ofw = new FileWindow();
                ofw.IsOpen = false;
                ofw.FileType = DoubleH.Utility.FileWindow.EnumFileType.商品控件的导入导出;
                ofw.ShowDialog();
                if (ofw.Canel)
                    return;

                StringBuilder sb = new StringBuilder();
                foreach (Table.ProductS ps in productSinObject)
                    sb.Append(ps.Id + "," + ps.Code + "," + ps.Barcode + "," + ps._TempPrice + "," + ps._TempQuantity + ","+ps.Note+"\r\n");

                File.WriteAllText(ofw.FileName, sb.ToString());
                MessageWindow.Show("导出成功");
            };

            return mi1;
        }

        #endregion

    }
}